package com.boesch.electroOffice.business.birt;

import org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportEngineFactory;

public class BirtEngine {
	private static IReportEngine birtEngine = null;

	@SuppressWarnings("unchecked")
	private static EngineConfig initializeEngineConfig(String birtHome, String resourceFolder,
			String odaJDBCDriverClassPath) {
		EngineConfig config = new EngineConfig();

		if (birtHome != null && birtHome.length() > 0) {
			config.setBIRTHome(birtHome);
		}
		if (resourceFolder != null && resourceFolder.length() > 0) {
			config.setResourcePath(resourceFolder);
		}
		if (odaJDBCDriverClassPath != null && odaJDBCDriverClassPath.length() > 0) {
			config.getAppContext().put("OdaJDBCDriverClassPath", odaJDBCDriverClassPath);
		}
		return config;
	}

	public static synchronized IReportEngine getBirtEngine(String birtHome, String resourceFolder,
			String odaJDBCDriverClassPath) {
		return getBirtEngine(initializeEngineConfig(birtHome, resourceFolder, odaJDBCDriverClassPath));
	}

	public static synchronized IReportEngine getBirtEngine(String birtHome, String resourceFolder) {
		return getBirtEngine(initializeEngineConfig(birtHome, resourceFolder, null));
	}

	private static IReportEngine getBirtEngine(EngineConfig config) {
		if (birtEngine == null) {
			try {
				Platform.startup(config);
				IReportEngineFactory factory = (IReportEngineFactory) Platform
						.createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY);
				birtEngine = factory.createReportEngine(config);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		return birtEngine;
	}

	public static void destroyEngine() {
		Platform.shutdown();
	}
}
